import { BaseController } from './BaseController.js';
import { UserModel } from '../model/UserModel.js';
import { UserDTO } from '../dto/UserDTO.js';
import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';
import { config } from '../config.js';

export class UserController extends BaseController {
    constructor() {
        const userModel = new UserModel();
        super(userModel);
        this.userModel = userModel;
    }

    // 获取所有用户（支持分页和搜索）
    async getAllUsers({ page = 1, limit = 10, search, status, role }) {
        try {
            const result = await super.getPaginatedData({
                page,
                limit,
                search,
                filters: { status, role },
                searchFields: ['username', 'email', 'first_name', 'last_name']
            });
            
            return {
                users: result.data.map(user => this._sanitizeUser(user)),
                pagination: result.pagination
            };
        } catch (error) {
            throw new Error(`Failed to get users: ${error.message}`);
        }
    }

    // 根据ID获取用户
    async getUserById(id) {
        try {
            const user = await super.getById(id);
            return this._sanitizeUser(user);
        } catch (error) {
            throw new Error(`Failed to get user: ${error.message}`);
        }
    }

    // 创建新用户
    async createUser(userData) {
        try {
            // 使用DTO验证用户数据
            const validation = UserDTO.validateCreate(userData);
            
            if (!validation.isValid) {
                const errorMessages = validation.errors.map(err => err.message).join(', ');
                throw new Error(`Validation failed: ${errorMessages}`);
            }
            
            const validatedData = validation.data;
            
            // 检查用户名和邮箱是否已存在
            const existingUser = await this.userModel.findByUsernameOrEmail(
                validatedData.username, 
                validatedData.email
            );
            
            if (existingUser) {
                throw new Error('Username or email already exists');
            }
            
            // 加密密码
            if (validatedData.password) {
                validatedData.password = await this._hashPassword(validatedData.password);
            }
            
            // 设置默认值
            const userToCreate = {
                ...validatedData,
                status: validatedData.status || 'active',
                role: validatedData.role || 'user'
            };
            
            const newUser = await super.create(userToCreate);
            return this._sanitizeUser(newUser);
        } catch (error) {
            throw new Error(`Failed to create user: ${error.message}`);
        }
    }

    // 更新用户
    async updateUser(id, updateData) {
        try {
            // 使用DTO验证更新数据
            const validation = UserDTO.validateUpdate(updateData);
            
            if (!validation.isValid) {
                const errorMessages = validation.errors.map(err => err.message).join(', ');
                throw new Error(`Validation failed: ${errorMessages}`);
            }
            
            const validatedData = validation.data;
            
            // 如果更新密码，需要加密
            if (validatedData.password) {
                validatedData.password = await this._hashPassword(validatedData.password);
            }
            
            // 检查用户名和邮箱唯一性（排除当前用户）
            if (validatedData.username || validatedData.email) {
                const existingUser = await this.userModel.findByUsernameOrEmailExcludeId(
                    validatedData.username || '',
                    validatedData.email || '',
                    id
                );
                
                if (existingUser) {
                    throw new Error('Username or email already exists');
                }
            }
            
            const updatedUser = await super.update(id, validatedData);
            return updatedUser ? this._sanitizeUser(updatedUser) : null;
        } catch (error) {
            throw new Error(`Failed to update user: ${error.message}`);
        }
    }

    // 删除用户
    async deleteUser(id) {
        try {
            return await super.delete(id);
        } catch (error) {
            throw new Error(`Failed to delete user: ${error.message}`);
        }
    }

    // 用户登录
    async loginUser(loginData) {
        try {
            // 使用DTO验证登录数据
            const validation = UserDTO.validateLogin(loginData);
            
            if (!validation.isValid) {
                const errorMessages = validation.errors.map(err => err.message).join(', ');
                throw new Error(`Validation failed: ${errorMessages}`);
            }
            
            const { email, password } = validation.data;
            
            // 查找用户（支持用户名或邮箱登录）
            const user = await this.userModel.findByUsernameOrEmail(email, email);
            
            if (!user) {
                throw new Error('Invalid credentials');
            }
            
            // 检查用户状态
            if (user.status !== 'active') {
                throw new Error('Account is not active');
            }
            
            // 验证密码
            const isPasswordValid = await this._verifyPassword(password, user.password);
            
            if (!isPasswordValid) {
                throw new Error('Invalid credentials');
            }
            
            // 更新最后登录时间
            await this.userModel.updateLastLogin(user.id);
            
            // 生成JWT token
            const token = this._generateToken(user);
            
            return {
                user: this._sanitizeUser(user),
                token
            };
        } catch (error) {
            throw new Error(`Login failed: ${error.message}`);
        }
    }

    // 密码重置请求
    async requestPasswordReset(resetData) {
        try {
            // 使用DTO验证密码重置数据
            const validation = UserDTO.validatePasswordReset(resetData);
            
            if (!validation.isValid) {
                const errorMessages = validation.errors.map(err => err.message).join(', ');
                throw new Error(`Validation failed: ${errorMessages}`);
            }
            
            const { email } = validation.data;
            
            // 查找用户
            const user = await this.userModel.findByUsernameOrEmail('', email);
            
            if (!user) {
                // 为了安全，不透露用户是否存在
                return { message: 'If the email exists, a reset link will be sent' };
            }
            
            // 这里可以添加发送重置邮件的逻辑
            // TODO: 实现邮件发送功能
            
            return { message: 'Password reset link sent to your email' };
        } catch (error) {
            throw new Error(`Password reset failed: ${error.message}`);
        }
    }
    
    // 更新密码
    async updatePassword(userId, passwordData) {
        try {
            // 使用DTO验证密码更新数据
            const validation = UserDTO.validatePasswordUpdate(passwordData);
            
            if (!validation.isValid) {
                const errorMessages = validation.errors.map(err => err.message).join(', ');
                throw new Error(`Validation failed: ${errorMessages}`);
            }
            
            const { current_password, new_password } = validation.data;
            
            // 获取用户当前信息
            const user = await this.userModel.findById(userId);
            if (!user) {
                throw new Error('User not found');
            }
            
            // 验证当前密码
            const isCurrentPasswordValid = await this._verifyPassword(current_password, user.password);
            if (!isCurrentPasswordValid) {
                throw new Error('Current password is incorrect');
            }
            
            // 加密新密码
            const hashedNewPassword = await this._hashPassword(new_password);
            
            // 更新密码
            await this.userModel.update(userId, { password: hashedNewPassword });
            
            return { message: 'Password updated successfully' };
        } catch (error) {
            throw new Error(`Password update failed: ${error.message}`);
        }
    }



    // 密码加密
    async _hashPassword(password) {
        const saltRounds = 10;
        return await bcrypt.hash(password, saltRounds);
    }

    // 密码验证
    async _verifyPassword(password, hashedPassword) {
        return await bcrypt.compare(password, hashedPassword);
    }

    // 生成JWT token
    _generateToken(user) {
        const payload = {
            id: user.id,
            username: user.username,
            email: user.email,
            role: user.role
        };
        
        return jwt.sign(payload, config.jwt.secret, {
            expiresIn: config.jwt.expiresIn
        });
    }

    // 移除敏感信息
    _sanitizeUser(user) {
        if (!user) return null;
        
        return super.sanitizeData(user, ['password']);
    }
}